import FileSaver from 'file-saver';
import XLSX from 'xlsx';
// import XLSX from 'xlsx-style';

export const exportExcel = (fileName, map, data) => {
  const wopts = {
    bookType: 'xlsx',
    bookSST: true,
    type: 'binary',
  };
  const workBook = {
    SheetNames: ['Sheet1'],
    Sheets: {},
    Props: {},
  };
  const table = [];
  table[0] = [fileName]; // 为设置表头流出空位
  for (let i = 0; i < Object.getOwnPropertyNames(map).length - 1; i++) {
    table[0].push(null);
  }
  table[1] = [];
  for (const key in map) {
    table[1].push(map[key]);
  }
  for (let i = 0; i < data.length; i++) {
  //  const params = {};
  //     for (const key in map) {
  //       params[map[key]] = data[i][key];
  //     }
  //     table[i] = params;
    table[i + 2] = [];
    for (const key in map) {
      table[i + 2].push(data[i][key]);
    }
  }

  // workBook.Sheets['Sheet1'] = XLSX.utils.json_to_sheet(table);
  workBook.Sheets['Sheet1'] = XLSX.utils.aoa_to_sheet(table);
  // 合并表头单元格
  workBook.Sheets['Sheet1']['!merges'] = [{
    e: { c: Object.getOwnPropertyNames(map).length - 1, r: 0 },
    s: { c: 0, r: 0 },
  }];
  // 设置表头样式
  workBook.Sheets['Sheet1']['A1'].s = { font: { sz: 14, bold: true, color: { rgb: 'FFFFAA00' }}, fill: { bgColor: { indexed: 64 }, fgColor: { rgb: 'FFFF00' }}};
  FileSaver.saveAs(new Blob([changeData(XLSX.write(workBook, wopts))], { type: 'application/octet-stream' }), `${fileName}.xlsx`);
};
const changeData = s => {
  if (typeof ArrayBuffer !== 'undefined') {
    const buf = new ArrayBuffer(s.length);
    const view = new Uint8Array(buf);

    for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
    return buf;
  } else {
    const buf = new Array(s.length);
    for (let i = 0; i !== s.length; ++i) buf[i] = s.charCodeAt(i) & 0xFF;
    return buf;
  }
};
